package com.mc.read.adminapi.manager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mc.read.common.util.HttpClient;
import com.mc.read.dao.mapper.PlugindownloadMapper;
import com.mc.read.dao.models.Plugindownload;
import com.mc.read.vo.respose.BaseRespose;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;

/**
 * @author liuhao
 * @date 2019/6/15 10:52
 */
@Component
@Slf4j
public class PublicManager {
    @Autowired
    PlugindownloadMapper plugindownloadMapper;
    /**
     * @Author:LiuHao
     * @Date:15:24 2019/5/31
     * 增加下载记录 addDownload
     **/
    public BaseRespose addDownload(HttpServletRequest request) {

        BaseRespose baseRespose = new BaseRespose();
        Browser browser = UserAgent.parseUserAgentString(request.getHeader("User-Agent")).getBrowser();
        Plugindownload plugindownload=new Plugindownload();
        plugindownload.setCreatedate(new Date());
        plugindownload.setBrowser(browser.toString());
        plugindownload.setVersion(browser.getVersion(request.getHeader("User-Agent")).getVersion());
        plugindownload.setIpadress(getIpAddress(request));
        try {
            if(!ObjectUtils.isEmpty(plugindownload.getIpadress())){
                String url="http://ip.taobao.com/service/getIpInfo.php?ip="+plugindownload.getIpadress();
//               String result= new HttpRequestor().doGet(url);
                String result= HttpClient.sendGet(url);
                JSONObject ipresult =  JSON.parseObject(result);
                Object object=ipresult.get("data");
                if(!ObjectUtils.isEmpty(object)){
                    JSONObject jsonObject=(JSONObject) object;
                    plugindownload.setRegion(jsonObject.get("region").toString());
                    plugindownload.setCity(jsonObject.get("city").toString());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        plugindownloadMapper.insertSelective(plugindownload);
        return baseRespose;
    }


    /**
     * 获取客户端ip
     *
     * @param request
     * @return
     */
    public String getIpAddress(HttpServletRequest request) {


        /**
         proxy_set_header Host $host;
         proxy_set_header X-Real-IP $remote_addr;
         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
         */
        String unknown = "unknown";

        String ipAddress = request.getHeader("x-remoter-ip");
        if (StringUtils.isEmpty(ipAddress) || unknown.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("x-forwarded-for");
        }
        if (StringUtils.isEmpty(ipAddress) || unknown.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ipAddress) || unknown.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ipAddress) || unknown.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();

            if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
                //根据网卡获取本机配置的IP地址
                InetAddress inetAddress = null;
                try {
                    inetAddress = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    log.error("UnknownHostException{}", e);
                }
                ipAddress = inetAddress.getHostAddress();
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实的IP地址，多个IP按照','分割
        if (null != ipAddress && ipAddress.length() > 15) {
            //"***.***.***.***".length() = 15
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }

        return ipAddress;
    }

    public static void main(String[] args) throws Exception {

        String str= HttpClient.sendGet("http://ip.taobao.com/service/getIpInfo.php?ip=125.76.213.242");
        System.out.println(str);

    }


}
